package com.rzico.sbl.ui.member

import android.graphics.Paint
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberChangeBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.GoodsData
import com.rzico.sbl.model.GoodsInput
import com.rzico.sbl.other.showPriceDialog
import com.rzico.sbl.ui.goods.GoodsActivity
import com.rzico.sbl.viewmodel.MemberViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class MemberChangeActivity : BaseActivity(R.layout.activity_member_change) {

    private val mBinding by lazy { ActivityMemberChangeBinding.bind(getRootView()) }

    private lateinit var mMemberId: String
    private var isEditMode = false

    override fun getViewModel() = get<MemberViewModel>()

    override fun initData() {
        initTitle(title = "商品改价", name = "编辑")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.apply {
            changeAll.setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

            listLayout.apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关商品信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            if (!isLoadingMore) {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<GoodsData>(R.layout.item_change_list) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_change_name, bean.name)
                                text(R.id.item_change_price, bean.vipPrice.formatDecimal())

                                with<TextView>(R.id.item_change_origin) {
                                    it.text = "原价：${bean.price.formatDecimal()}"
                                    it.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                                }

                                with<ImageView>(R.id.item_change_logo) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<ImageView>(R.id.item_change_check) {
                                    it.isVisible = isEditMode
                                    it.setImageResource(
                                        conditionIf(
                                            bean.check,
                                            R.mipmap.login_yes_orange,
                                            R.mipmap.login_no
                                        )
                                    )
                                    it.oneClick {
                                        bean.check = !bean.check
                                        notifyItemChanged(index)

                                        checkTextHint()
                                    }
                                }

                                with<TextView>(R.id.item_change_modify) {
                                    it.gone = isEditMode

                                    it.oneClick {
                                        updatePrice(
                                            bean.productId,
                                            bean.name,
                                            bean.vipPrice,
                                            index
                                        )
                                    }
                                }

                                with<EditText>(R.id.item_change_input) {
                                    it.isVisible = isEditMode

                                    if (it.tag != null && it.tag is TextWatcher) {
                                        it.removeTextChangedListener(it.tag as TextWatcher)
                                    }

                                    it.filters = arrayOf(
                                        DecimalNumberFilter(),
                                        InputFilter.LengthFilter(8)
                                    )
                                    it.setText(bean.vip1Price)
                                    it.setSelection(it.text.length)

                                    val textWatcher = object : _TextWatcher() {
                                        override fun afterTextChanged(s: Editable) {
                                            bean.vip1Price = s.toString()
                                        }
                                    }
                                    it.addTextChangedListener(textWatcher)
                                    it.tag = textWatcher
                                }

                                longClicked {
                                    if (!isEditMode)
                                        deletePrice(bean.id, index)
                                    true
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }

            tvRight?.oneClick { view ->
                view as TextView
                isEditMode = !isEditMode

                isEditMode
                    .apply {
                        view.text = conditionIf(this, "取消", "编辑")
                        changeEdit.isInvisible = !this
                        btAdd.isGone = this
                    }
                    .condition {
                        mList.forEach {
                            it as GoodsData
                            it.check = false
                        }

                        checkTextHint()
                    }

                mAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initListener() {
        mMemberId = intent.getExtra("memberId")

        mBinding.apply {
            btDel.oneClick {
                mList.none { (it as GoodsData).check }
                    .condition {
                        showToast("请选择要删除的商品")
                        return@oneClick
                    }

                deletePrice(
                    mList.filter { (it as GoodsData).check }
                        .joinToString(",") { (it as GoodsData).id },
                    -1
                )
            }

            btChange.oneClick {
                mList.none { (it as GoodsData).check }
                    .condition {
                        showToast("请选择要改价的商品")
                        return@oneClick
                    }

                val inputList = mList
                    .filter { (it as GoodsData).check }
                    .map {
                        it as GoodsData

                        GoodsInput(
                            productId = it.productId,
                            price = it.vip1Price,
                            name = it.name
                        )
                    }

                inputList.any { it.price.isEmpty() }
                    .condition {
                        showToast("请确认已输入选中商品改价金额")
                        return@oneClick
                    }

                getViewModel()
                    .requestBind(
                        requestUrl = BaseUrl.priceMulti,
                        params = arrayOf(
                            "memberId" to mMemberId,
                            "body" to Gson().toJson(inputList)
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("批量改价成功！")

                            updateList()
                        }
                    )
            }

            btAdd.oneClick {
                startActivityEx<GoodsActivity>(
                    "mode" to "multiple",
                    "hint" to "请选择要改价的商品"
                )
            }
        }

        observe<String>("goodsMultiple") {
            getViewModel().delay {
                getViewModel()
                    .requestBind(
                        requestUrl = BaseUrl.priceMulti,
                        params = arrayOf(
                            "memberId" to mMemberId,
                            "productIds" to it
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            updateList()

                            isEditMode = !isEditMode
                            isEditMode
                                .apply {
                                    tvRight?.text = conditionIf(
                                        this,
                                        "取消",
                                        "编辑"
                                    )

                                    mBinding.changeEdit.isInvisible = !this
                                    mBinding.btAdd.isGone = this
                                }

                            checkTextHint()
                        }
                    )
            }
        }
    }

    private fun checkTextHint() {
        mBinding.apply {
            changeAll.apply {
                setOnCheckedChangeListener(null)
                isChecked =
                    mList.isNotEmpty() && mList.none { !(it as GoodsData).check }
                setOnCheckedChangeListener(this@MemberChangeActivity)
            }

            btDel.text = "删除(${mList.count { (it as GoodsData).check }})"
            btChange.text = "一键改价(${mList.count { (it as GoodsData).check }})"
        }
    }

    /**
     * 删除改价
     */
    private fun deletePrice(itemId: String, index: Int) {
        showHintDialog(
            title = "删除商品",
            hint = "确定要删除商品吗？",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.priceDel,
                        params = arrayOf("ids" to itemId),
                        onSuccess = {
                            showToast("商品删除成功！")

                            if (index < 0) {
                                val ids = itemId.split(",")
                                ids.forEach { id ->
                                    mList.removeAll { (it as GoodsData).id == id }
                                }

                                mAdapter.notifyDataSetChanged()

                                checkTextHint()
                            } else {
                                mList.removeAt(index)
                                mAdapter.apply {
                                    notifyItemRemoved(index)
                                    notifyItemRangeChanged(index, mList.size - index)
                                }
                            }
                        }
                    )
            }
        )
    }

    /**
     * 订单改价
     */
    private fun updatePrice(
        productId: String,
        goodsName: String,
        amount: String,
        index: Int
    ) {
        showPriceDialog(
            title = "商品改价",
            hint = goodsName,
            default = amount,
            onSure = { value ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.priceChange,
                        params = arrayOf(
                            "memberId" to mMemberId,
                            "productId" to productId,
                            "price" to value
                        ),
                        onSuccess = {
                            showToast("商品改价成功！")

                            if (index < 0) updateList()
                            else {
                                (mList[index] as GoodsData).vipPrice = value
                                mAdapter.notifyItemChanged(index)
                            }
                        }
                    )
            }
        )
    }

    /**
     * 改价列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .changeList(
                page = index,
                member = mMemberId,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)

                    if (isEditMode) checkTextHint()
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as GoodsData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        checkTextHint()
    }

}